import Immutable from 'seamless-immutable'
import { createSlice } from '@reduxjs/toolkit'
import { AnyAction } from 'redux'
import createRequestTypes from '@UTILS/reduxHelper'
import { UpdateInfo } from '@TYPES/App'
import fetchUpdateStatue from '../thunk/user'

const USER = createRequestTypes('USER')
export interface User {
  AcquireChannel: string,
  p8Id: string,
  UserName: string,
  NickName: {
    en: string
    es: string
  }
}
const INITIAL_STATE = Immutable({
  user: {
    user: {
      AcquireChannel: '',
      p8Id: '',
      UserName: '',
      NickName: {
        en: '',
        es: '',
      },
      DeviceUUID: '',
    } as User,
  },
  appUpdatInfo: {
    ForceUpdate: false,
    NeedUpdate: false,
    UpdateDescription: [
      {
        en: '',
        zh: '',
      },
    ],
    UpdateTitle: {
      en: '',
      zh: '',
    },
    Version: '',
  } as UpdateInfo,
})

const userSlice = createSlice({
  name: 'user',
  initialState: INITIAL_STATE,
  reducers: {
    loginSuccess: (state, action) => ({
      ...state,
      user: action.payload,
    }),
    updateDeviceUUID: (state, action) => ({
      ...state,
      user: { ...state.user, DeviceUUID: action.payload },
    }),
    [USER.SUCCESS]: (state, action: AnyAction) => {
      console.log(action.payload)
      return {
        ...state,
      }
    },
    getUpdateInfoSuccess: (state, action) => ({
      ...state,
      user: action.payload,
    }),
  },
  extraReducers: (builder) => {
    builder.addCase(fetchUpdateStatue.fulfilled, (state, action) => {
      // eslint-disable-next-line no-param-reassign
      state.appUpdatInfo = action.payload
    })
  },
})

const { actions } = userSlice
export { actions, USER }

export default userSlice.reducer
